<?php
class ProductService
{
	private $searchService;
	private $prodcutSearchResult;
	
	private $userId;
	private $useCache;
	
	public function __construct(){
		$this->searchService	= C('SearchService');
		$this->useCache			= true;
		$this->userId			= 0;
	}
	
	public function getProductById($id,$detail=false)
	{
		$product	= $this->getTaoKeProductByNumId($id);
		if(!$product && $detail)
		{
			$product	= $this->getTaobaoItem($id);
		}
		return $product;
	}
	
	public function getTaoKeProductByNumId($id,$fields=array())
	{
		if(!is_numeric($id))
		{
			return false;
		}
		$config = C('SettingService')->get('config_setting',true);
		//从cache中取数据
		$product		= $this->getDataFromCache($id,'detail');
		if(!$product || ($config['detail']['showcontent'] && !array_key_exists('desc',$product['item'])))
		{
			$product = false;
		}
		if($product)
		{
			if(!array_key_exists('commission',$product))
			{
				$returnSetting = C('SettingService')->get('return_setting',true);
				//判断是否开启了返利
				if($returnSetting['rate']>0)
				{
					$commission = $this->getProductCommission($id);
					if($commission)
					{
						foreach($commission as $k=>$v)
						{
							$product['commission'][$k]	= $v;
						}
					}
					$this->saveDataToCache($id,'detail',$product);
				}
			}
			
			return $product;
		}
		//初始化查询的字段
		$cols		= split(',','iid,click_url,shop_click_url,seller_credit_score,detail_url,num_iid,title,nick,type,cid,seller_cids,input_pids,input_str,pic_url,num,valid_thru,list_time,delist_time,stuff_status,location,price,post_fee,express_fee,ems_fee,has_discount,freight_payer,has_invoice,has_warranty,has_showcase,modified,increment,auto_repost,approve_status,postage_id,product_id,auction_point,property_alias,outer_id,is_virtural,is_taobao,is_ex,video,is_3D,one_station');
		//获取详细描述
		if($config['detail']['showcontent'])
		{
			$cols[]	= 'desc';
		}
		$fields		= $this->checkFields($cols,$fields);
		
		$apiSetting		= C('SettingService')->get('api_setting',true);
		//参数
		$params			= array(
			'method' 	=> 'taobao.taobaoke.items.detail.get',
			'fields' 	=> $fields,
			'nick' 		=> $apiSetting['taobao_api_nick'],
			'pid' 		=> C('CommonFunction')->getPid($apiSetting['taobao_api_pid']),
			'num_iids' 	=> $id,
			'outer_code'	=> $this->userId,
		);
		
		$num			= $apiSetting['taobao_api_num'];
		if($num<=0)
		{
			$num		= 1;
		}
		else if($num>3)
		{
			$num		= 3;
		}
		for($i=0;$i<$num;$i++)
		{
			$tmp 			= $this->searchService->getResult($params);
			if($tmp && !array_key_exists('error_response',$tmp))
			{
				break;
			}
		}
		if(!$tmp || !array_key_exists('taobaoke_items_detail_get_response', $tmp)){
			return false;
		}
		
		$product	= array_key_exists('taobaoke_item_details', $tmp['taobaoke_items_detail_get_response'])?$tmp['taobaoke_items_detail_get_response']['taobaoke_item_details']['taobaoke_item_detail'][0]:false;
		
		//判断是否开启了返利
		$returnSetting = C('SettingService')->get('return_setting',true);
		if($returnSetting['rate']>0)
		{
			$commission = $this->getProductCommission($id);
			if($commission)
			{
				foreach($commission as $k=>$v)
				{
					$product['commission'][$k]	= $v;
				}
			}
		}
		//保存到cache中
		$this->saveDataToCache($id,'detail',$product);
		return $product;
	}
	
	public function getList($con,$fields=array(),$cache=0,$position='')
	{
		//从缓存中获取
		$cacheId		= md5(serialize($con).serialize($fields).$cache.$position);
		if($cache>0)
		{
			$result	= $this->getListFromCache($cacheId);
			if($result)
			{
				return $result;
			}
		}
		
		$this->searchTaoKeProducts($con,$fields,false);
		$result		= $this->getProductList();
		//更新cache
		if($cache>0 && $result)
		{
			$this->saveListToCache($cacheId,$result,$cache);
		}
		return $result;
	}
	
	public function getListFromCacheByCondition($con,$fields=array(),$cache=0,$position='')
	{
		if(empty($cache))
		{
			$cache = 3600;
		}
		return $this->getList($con,$fields,$cache,$position);
	}
	
	public function searchTaoKeProducts($con,$fields=array(),$cache=true,$spider=false)
	{
		//初始化查询的字段
		$cols		= split(',','iid,num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location');
		$fields		= $this->checkFields($cols,$fields);
		
		if(array_key_exists('ids',$con))
		{
			//有num_iid
			if($con['ids']!='')
			{
				return $this->getProductListByIds($con['ids'], $fields,$cache);
			}
			else
			{
				unset($con['ids']);
			}
		}
		
		if(!$con['cid'])
		{
			unset($con['cid']);
		}
		
		if(empty($con['cid']) && empty($con['keyword']))
		{
			$this->prodcutSearchResult	= false;
			return false;
		}
		
		if(!is_numeric($con['page_size']))
		{
			$con['page_size']	= 40;
		}
		
		$products2 		= $this->getRelateListProduct($con,10,$spider,'');
		if($products2)
		{
			$con['page_size']	= $con['page_size']-count($products2);
			if($con['page_size']<0)
			{
				$con['page_size'] = 1;
			}
		}
		
		$apiSetting		= C('SettingService')->get('api_setting',true);
		
		//参数
		$params			= array(
			'method' 	=> 'taobao.taobaoke.items.get',
			'fields' 	=> $fields,
			'nick'		=> $apiSetting['taobao_api_nick'],
			'pid' 		=> C('CommonFunction')->getPid($apiSetting['taobao_api_pid']),
		);
		$params			= array_merge($params,$con);
		
		$products		= false;
		if($cache)
		{
			$cacheId		= md5(serialize($params));
			$products		= $this->getDataFromCache($cacheId,'list');
		}
		if(!$products)
		{
			$num			= $apiSetting['taobao_api_num'];
			if($num<=0)
			{
				$num		= 1;
			}
			else if($num>3)
			{
				$num		= 3;
			}
			for($i=0;$i<$num;$i++)
			{
				$tmp 			= $this->searchService->getResult($params);
				if($tmp && !array_key_exists('error_response',$tmp))
				{
					break;
				}
			}
			
			if(!$tmp || !array_key_exists('taobaoke_items_get_response', $tmp))
			{
				$this->prodcutSearchResult	= false;
				return false;
			}
			
			$products	= $tmp['taobaoke_items_get_response'];
			if($cache)
			{
				$this->saveDataToCache($cacheId,'list',$products);
			}
		}
		
		if(count($products['taobaoke_items']['taobaoke_item'])>$con['page_size'])
		{
			for($i=count($products['taobaoke_items']['taobaoke_item'])-1;$i>=$con['page_size'];$i--)
			{
				unset($products['taobaoke_items']['taobaoke_item'][$i]);
			}
		}
		if(!$products['taobaoke_items']['taobaoke_item'])
		{
			$products['taobaoke_items']['taobaoke_item'] = array();
		}
		
		if($products2)
		{
			$products['taobaoke_items']['taobaoke_item']	= array_merge($products2,$products['taobaoke_items']['taobaoke_item']);
		}
		
		$this->prodcutSearchResult	= $products;
		return $products;
	}
	
	private function getProductListByIds($ids,$fields,$cache=true)
	{
		$ids			= str_replace('，',',',$ids);
		
		$result			= false;
		if($cache)
		{
			$cacheId	= md5($ids.$fields);
			$result		= $this->getDataFromCache($cacheId,'idlist');
		}
		
		if(!$result)
		{
			$apiSetting	= C('SettingService')->get('api_setting',true);
			
			$products	= array();
			$idList		= explode(',',$ids);
			for($ii=0;$ii<count($idList);$ii+=40)
			{
				$maxLen			= count($idList)-$ii>=40?40:count($idList)-$ii;
				//参数
				$params			= array(
							'method' 	=> 'taobao.taobaoke.items.convert',
							'fields' 	=> $fields,
							'nick'		=> $apiSetting['taobao_api_nick'],
							'pid' 		=> C('CommonFunction')->getPid($apiSetting['taobao_api_pid']),
							'num_iids' 	=> implode(',',array_slice($idList,$ii,$maxLen))
				);
				
				$num			= $apiSetting['taobao_api_num'];
				if($num<=0)
				{
					$num		= 1;
				}
				else if($num>3)
				{
					$num		= 3;
				}
				for($i=0;$i<$num;$i++)
				{
					$tmp		= $this->searchService->getResult($params);
					if($tmp && !array_key_exists('error_response',$tmp))
					{
						break;
					}
				}
				if(!$tmp || !array_key_exists('taobaoke_items_convert_response', $tmp))
				{
					continue;
				}
				
				$products	= array_merge($products, $tmp['taobaoke_items_convert_response']['taobaoke_items']['taobaoke_item']);
			}
			
			$result['taobaoke_items']['taobaoke_item']	= $products;
			$result['total_results']					= count($products);
			
			if($cache)
			{
				$this->saveDataToCache($cacheId,'idlist',$result);
			}
		}
		
		$this->prodcutSearchResult	= $result;
		return $result;
	}
	
	private function getRelateListProduct($con,$num,$spider,$fields='')
	{
		if($con['page_no']>1)
		{
			return false;
		}
		$relateSetting		= C('SettingService')->get('list_relate_setting',true);
		$relate				= false;
		if(array_key_exists('cid',$con) && array_key_exists('cid',$relateSetting))
		{
			//检查类目
			$catList = C('CategoryService')->getParentList($con['cid']);
			foreach($catList as $cat)
			{
				if($cat['id']==$relateSetting['cid'])
				{
					$relate = true;
					break;
				}
			}
		}
		if(!$relate && array_key_exists('keyword',$con) && array_key_exists('keyword',$relateSetting))
		{
			//检查关键词
			$keywords = explode(',',$relateSetting['keyword']);
			if(in_array($con['keyword'],$keywords))
			{
				$relate = true;
			}
		}
		if(!$relate)
		{
			return false;
		}
		
		$params			= array(
			'method' 	=> 'taobao.taobaoke.items.related.list',
			'cid'		=> $con['cid'],
			'q'			=> $con['keyword'],
			'page_size'	=> $num,
			'spider'	=> $spider,
			'fields'	=> $fields,
			'pisces'	=> true
		);
		if($con['is_module']==1)
		{
			$params['type']	= 1;
		}
		$tmp 			= $this->searchService->getResult($params);
		if(!$tmp || !array_key_exists('code', $tmp) || $tmp['code']!=200)
		{
			return false;
		}
		return $tmp['data']['taobaoke_item_related_list_get_response'];
	}
	
	private function getDataFromCache($id,$type)
	{
		if(!$this->useCache)
		{
			return false;
		}
		$cacheCfg	= C('LtConfig')->get('cache.product');
		if($type=='list')
		{
			$enable		= $cacheCfg['listcacheenable'];
			$period		= $cacheCfg['listcacheperiod'];
			$cacheDir	= $cacheCfg['listdir'];
		}
		else
		{
			$enable		= $cacheCfg['detailcacheenable'];
			$period		= $cacheCfg['detailcacheperiod'];
			$cacheDir	= $cacheCfg['detaildir'];
		}
		
		if(!$enable)
		{
			return false;
		}
		
		//获取所在的日期目录
		$createDate	= $this->getCacheCreateDate($id,$type);
		if($createDate==0)
		{
			return false;
		}
		//判断是否已经过期的，过期的清空这天的缓存数据
		$du		= C('DateUtil');
		$start	= date('Ymd',$du->dateAdd('d',0-$period,date('Y-m-d')));
		if($createDate<$start)
		{
			//清空这天的缓存数据
			$productCacheService = new ProductCacheService();
			$productCacheService->deleteByDate($createDate);
			return false;
		}
			
		$cacheDir	.= $createDate.'/';
		
		$ccs		= C('CompressCacheService');
		$d			= $ccs->getCacheDirById($id);
		if($d===false)
		{
			return false;
		}
		$result	= $ccs->getCacheData($cacheDir,$d,$id);
		//检查过期时间
		if($result)
		{
			//没有缓存时间或者缓存时间距离当前时间已经超过设定的cache时间
			if(!array_key_exists('cache_time',$result) || $du->dateAdd('d',$period,$result['cache_time'])<strtotime(date('Y-m-d')))
			{
				$result	= false;
			}
		}
		
		return $result;
	}
	
	private function saveDataToCache($id,$type,$data)
	{
		if(!$data || !$this->useCache)
		{
			return false;
		}
		
		$cacheCfg	= C('LtConfig')->get('cache.product');
		if($type=='list')
		{
			$enable		= $cacheCfg['listcacheenable'];
			$period		= $cacheCfg['listcacheperiod'];
			$cacheDir	= $cacheCfg['listdir'];
		}
		else
		{
			$enable		= $cacheCfg['detailcacheenable'];
			$period		= $cacheCfg['detailcacheperiod'];
			$cacheDir	= $cacheCfg['detaildir'];
		}
		
		if(!$enable)
		{
			return false;
		}
		
		$created	= date('Ymd');
		$res		= $this->saveProductCacheDate($id,$type,$created);
		if(!$res)
		{
			return false;
		}
		$cacheDir	.= $created.'/';
		
		$ccs		= C('CompressCacheService');
		$d			= $ccs->getCacheDirById($id);
		if($d===false)
		{
			return false;
		}
		$data['cache_time']	= date('Y-m-d');
		$ccs->setCacheData($cacheDir,$d,$id,$data);
		
		return true;
	}
	
	public function getTotalProcuct()
	{
		if(is_array($this->prodcutSearchResult) && array_key_exists('total_results', $this->prodcutSearchResult)){
			return $this->prodcutSearchResult['total_results'];
		}
		return 0;
	}
	
	public function getProductList()
	{
		if(is_array($this->prodcutSearchResult) && array_key_exists('taobaoke_items', $this->prodcutSearchResult)){
			return $this->prodcutSearchResult['taobaoke_items']['taobaoke_item'];
		}
		return false;
	}
	
	public function getListUrl($keyword)
	{
		$apiSetting		= C('SettingService')->get('api_setting',true);
		
		$params			= array(
			'method' 	=> 'taobao.taobaoke.listurl.get',
			'nick'		=> $apiSetting['taobao_api_nick'],
			'pid' 		=> C('CommonFunction')->getPid($apiSetting['taobao_api_pid']),
			'q'			=> $keyword,
		);
		$tmp 			= $this->searchService->getResult($params);
		if(!$tmp || !array_key_exists('taobaoke_listurl_get_response', $tmp))
		{
			return false;
		}
		return $tmp['taobaoke_listurl_get_response']['taobaoke_item']['keyword_click_url'];
	}
	
	public function setUserId($id)
	{
		$this->userId	= $id;
		$this->useCache	= $id>0?false:true;
	}
	
	public function getRelatedProduct($cid,$keyword,$num,$spider,$fields='')
	{
		$params			= array(
			'method' 	=> 'taobao.taobaoke.items.related',
			'cid'		=> $cid,
			'q'			=> $keyword,
			'page_size'	=> $num,
			'spider'	=> $spider,
			'fields'	=> $fields,
			'pisces'	=> true
		);
		$tmp 			= $this->searchService->getResult($params);
		if(!$tmp || !array_key_exists('code', $tmp) || $tmp['code']!=200)
		{
			return false;
		}
		return $tmp['data']['taobaoke_item_related_get_response'];
	}
	
	public function getClick($id)
	{
		//初始化查询的字段
		$cols		= split(',','title,nick,click_url,shop_click_url');
		$fields		= $this->checkFields($cols,$fields);
		
		$apiSetting		= C('SettingService')->get('api_setting',true);
		//参数
		$params			= array(
			'method' 	=> 'taobao.taobaoke.items.convert',
			'fields' 	=> $fields,
			'nick'		=> $apiSetting['taobao_api_nick'],
			'pid' 		=> C('CommonFunction')->getPid($apiSetting['taobao_api_pid']),
			'num_iids' 	=> $id,
			'outer_code'	=> $this->userId,
		);
		
		$num			= $apiSetting['taobao_api_num'];
		if($num<=0)
		{
			$num		= 1;
		}
		else if($num>3)
		{
			$num		= 3;
		}
		for($i=0;$i<$num;$i++)
		{
			$tmp 			= $this->searchService->getResult($params);
			if($tmp && !array_key_exists('error_response',$tmp))
			{
				break;
			}
		}
		if(!$tmp || !array_key_exists('taobaoke_items_convert_response', $tmp)){
			return false;
		}
		
		$click	= array_key_exists('taobaoke_items', $tmp['taobaoke_items_convert_response'])?$tmp['taobaoke_items_convert_response']['taobaoke_items']['taobaoke_item'][0]:false;
		return $click;
	}
	
	private function getProductCommission($id,$fields='')
	{
		//初始化查询的字段
		$cols		= split(',','commission_rate,commission,commission_num,commission_volume');
		$fields		= $this->checkFields($cols,$fields);
		
		$apiSetting		= C('SettingService')->get('api_setting',true);
		//参数
		$params			= array(
			'method' 	=> 'taobao.taobaoke.items.convert',
			'fields' 	=> $fields,
			'nick'		=> $apiSetting['taobao_api_nick'],
			'pid' 		=> C('CommonFunction')->getPid($apiSetting['taobao_api_pid']),
			'num_iids' 	=> $id,
		);
		
		$num			= $apiSetting['taobao_api_num'];
		if($num<=0)
		{
			$num		= 1;
		}
		else if($num>3)
		{
			$num		= 3;
		}
		for($i=0;$i<$num;$i++)
		{
			$tmp 			= $this->searchService->getResult($params);
			if($tmp && !array_key_exists('error_response',$tmp))
			{
				break;
			}
		}
		if(!$tmp || !array_key_exists('taobaoke_items_convert_response', $tmp)){
			return false;
		}
		
		$commission	= array_key_exists('taobaoke_items', $tmp['taobaoke_items_convert_response'])?$tmp['taobaoke_items_convert_response']['taobaoke_items']['taobaoke_item'][0]:false;
		return $commission;
	}
	
	private function getTaobaoItem($id)
	{
		return false;
	}
	
	private function checkFields($allow,$fields)
	{
		if(!empty($fields))
		{
			$tmp	= array();
			foreach($fields as $f)
			{
				if(in_array($f, $allow))
				{
					$tmp[]	= $f;
				}
			}
			$fields	= $tmp;
		}
		if(empty($fields))
		{
			$fields		= $allow;
		}
		$fields			= implode(',', $fields);
		return $fields;
	}
	
	private function getListFromCache($id)
	{
		$cache 	= new LtCache();
		$cache->init();
		$ch 	= $cache->getTDG(C('LtConfig')->get('db.table.prefix')."product".$id);
		
		$result	= $ch->get('list');
		return $result;
	}
	
	private function saveListToCache($id,$data,$ttl)
	{
		$cache 	= new LtCache();
		$cache->init();
		$ch 	= $cache->getTDG(C('LtConfig')->get('db.table.prefix')."product".$id);
		
		$tmp	= $ch->get('list');
		if($tmp!==false)
		{
			$ch->update('list',$data,$ttl);
		}
		else
		{
			$ch->add('list',$data,$ttl);
		}
	}
	
	private function getCacheCreateDate($id,$type)
	{
		if($type=='list')
		{
			$prefix	= 'l_';
		}
		else
		{
			$prefix	= 'd_';
		}
		$id		= $prefix.$id;
		$node	= $this->getCacheTableNode($id);
		$productCacheDao	= new ProductCacheDao($node);
		$tmp	= $productCacheDao->get($id);
		if($tmp)
		{
			return $tmp['created'];
		}
		return 0;
	}
	
	private function saveProductCacheDate($id,$type,$created)
	{
		if($type=='list')
		{
			$prefix	= 'l_';
		}
		else
		{
			$prefix	= 'd_';
		}
		$id		= $prefix.$id;
		$node	= $this->getCacheTableNode($id);
		$productCacheDao	= new ProductCacheDao($node);
		$id	= $productCacheDao->add(array('id'=>$id,'created'=>$created));
		if($id)
		{
			return $id;
		}
		return false;
	}
	
	//根据id获取数据在那个表中
	private function getCacheTableNode($id)
	{
		$hashCode = 0;
        for($i=0, $len=strlen($id);$i<$len;$i++) {
            $hashCode = (int)(($hashCode*33)+ord($id[$i])) & 0x7fffffff;
        }
        return $hashCode%10+1;
	}
}
?>